<?php

namespace Task\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;

class TaskModel extends BaseModel {

    protected $_auto = [
        ['add_time', 'time', self::MODEL_INSERT, 'function'],
    ];
    protected $_validate = [
    ];
    protected $_scope = [
        
    ];

    public function addDoneTask($uid=0, $taskid=0) {
        $taskdone = D('TaskDone');
        $id = $taskdone->add(['user_id' => $uid, 'task_id' => $taskid, 'time' => time()]);
        
        return TRUE;
    }
    
    public function taskOnceRedis($uid,$key,$id) {
        $redis = redis();
        $mytask = $redis->sIsMember($key,$id);
        if(empty($mytask)){
            $redis->sAdd($key,$id);
            $trans = M();
            $trans->startTrans();
            $result = $this->addDoneTask($uid,$id);
            if($result){
                $task = D('Task')->find($id);//id表示任务id
                $res1= D('User')->where(['id'=>$uid])->setInc('gold',$task['description']);
                $res2 = D('Account/GoldLog')->addGoldLog(['user_id'=>$uid,'mark'=>$task['title'],'gold'=>$task['description'],'add_time'=>time(),'type'=>'send']);
                if(!empty($res1) && !empty($res2)){
                    $trans->commit();
                }else{
                    $trans->rollback();
                }
            }
        }
        return true;
    }
    
    //每日任务
    public function taskDayRedis($uid,$key,$id) {
        $redis = redis();
        $value = $uid.'_'.$id;
        $mytask = $redis->sIsMember($key,$value);
        if(!$mytask){
            $redis->sAdd($key,$value);
            $trans = M();
            $trans->startTrans();
            $result = $this->addDoneTask($uid,$id);//写入完成任务表
            if($result){
                $task = D('Task')->find($id);//id表示任务id
                $res1= D('User')->where(['id'=>$uid])->setInc('gold',$task['description']);
                $res2 = D('Account/GoldLog')->addGoldLog(['user_id'=>$uid,'mark'=>$task['title'],'gold'=>$task['description'],'add_time'=>time(),'type'=>'send']);
                if(!empty($res1) && !empty($res2)){
                    $trans->commit();
                }else{
                    $trans->rollback();
                }
            }
        }
        return true;
    }
    
    public function _after_insert($data,$options) {
        
    }

}
